<?php

// 主模型类
class MainModel extends Model {
	// 获得主页的博客列表, 提取出文章开头的内容
	public function get_blog_list($cate, $start, $num) {
		$db = DB::get_instance();
		if ($cate == "all") {
			$cate_query = " ";
		} else {
			$cate = (int)$cate;
			$cate_query = " WHERE category_id=$cate ";
		}
		$start = (int)$start;
		$num = (int)$num;
		$sql = "SELECT * FROM entries".$cate_query." 
				ORDER BY last_modified DESC LIMIT $start, $num";
		$r = $db->query($sql);
		$entries = $r->fetchAll();
		$this->shorten_body($entries, NUM_WORDS);
		return $entries;
	}
	// 通过 id 获取完整文章
	public function get_article($id) {
		$db = DB::get_instance();
		$sql = "SELECT * FROM entries INNER JOIN categories USING(category_id) WHERE entry_id=?";
		$stmt = $db->prepare($sql);
		$stmt->execute(array($id));
		return $stmt->fetch();
	}
	public function get_article_count($cate) {
		$db = DB::get_instance();
		$sql = "SELECT COUNT(entry_id) as cnt FROM entries";
		if ($cate != "all") {
			$cate = (int)$cate;
			$sql .= " WHERE category_id=$cate ";
		}
		$r = $db->query($sql);
		$r = $r->fetch();
		return $r["cnt"];
	}
	public function get_categories() {
		$db = DB::get_instance();
		$r = $db->query("SELECT category_id, name FROM categories");
		$ids = array();
		$names = array();
		foreach ($r as $one) {
			$ids[] = $one["category_id"];
			$names[] = $one["name"];
		}
		return array($ids, $names);
	}
	public function send_comment($entry_id, $name, $email, $comment) {
		$db = DB::get_instance();
		$stmt = $db->prepare("INSERT INTO comments (entry_id, name, email, body)
							  VALUES (?,?,?,?)");
		$r = $stmt->execute(array($entry_id, $name, $email, $comment));
		return $r;
	}
	public function get_article_comments($entry_id) {
		$db = DB::get_instance();
		$stmt = $db->prepare("SELECT comment_id, name, email, body, comment_date
						 FROM comments WHERE entry_id=?");
		$stmt->execute(array($entry_id));
		return $stmt->fetchAll();
	}
	// 将完整的文章列表中的正文缩短
	private function shorten_body(&$entries, $num_words) {
		for ($i = 0; $i < count($entries); $i++) { 
			$entries[$i]['body'] = mb_substr(
				strip_tags($entries[$i]['body']), 0, $num_words, 'utf-8').
				("...");
		}
	}
}